<template>
  <div class="admin-dashboard">
    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <h2>管理员控制台</h2>
        <p>欢迎回来，{{ userInfo.username }}</p>
      </div>
      <div class="header-right">
        <button class="logout-btn" @click="handleLogout">
          <i class="fas fa-sign-out-alt"></i>
          退出登录
        </button>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-icon user-stat">
          <i class="fas fa-users"></i>
        </div>
        <div class="stat-info">
          <h3>{{ stats.userCount }}</h3>
          <p>用户总数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon application-stat">
          <i class="fas fa-store"></i>
        </div>
        <div class="stat-info">
          <h3>{{ stats.pendingApplications }}</h3>
          <p>待审核申请</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon business-stat">
          <i class="fas fa-shop"></i>
        </div>
        <div class="stat-info">
          <h3>{{ stats.businessCount }}</h3>
          <p>店铺总数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon order-stat">
          <i class="fas fa-file-alt"></i>
        </div>
        <div class="stat-info">
          <h3>{{ stats.orderCount }}</h3>
          <p>订单总数</p>
        </div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="admin-menu">
      <div class="menu-section">
        <h3>用户管理</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="toUserManagement">
            <i class="fas fa-user-friends"></i>
            <span>用户列表</span>
          </div>
          <div class="menu-item" @click="toAddUser">
            <i class="fas fa-user-plus"></i>
            <span>新增用户</span>
          </div>
          <div class="menu-item" @click="toAddPerson">
            <i class="fas fa-user-edit"></i>
            <span>新增自然人</span>
          </div>
        </div>
      </div>

      <div class="menu-section">
        <h3>开店申请管理</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="toApplicationList">
            <i class="fas fa-clipboard-list"></i>
            <span>申请列表</span>
          </div>
          <div class="menu-item" @click="toPendingApplications">
            <i class="fas fa-clock"></i>
            <span>待审核申请</span>
            <span class="badge" v-if="stats.pendingApplications > 0">
              {{ stats.pendingApplications }}
            </span>
          </div>
        </div>
      </div>

      <div class="menu-section">
        <h3>店铺管理</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="toBusinessManagement">
            <i class="fas fa-store"></i>
            <span>店铺列表</span>
          </div>
        </div>
      </div>

      <div class="menu-section">
        <h3>钱包规则管理</h3>
        <div class="menu-grid">
          <div class="menu-item" @click="toWithdrawRuleManagement">
            <i class="fas fa-money-bill-wave"></i>
            <span>提现规则</span>
          </div>
          <div class="menu-item" @click="toRechargeRuleManagement">
            <i class="fas fa-credit-card"></i>
            <span>充值规则</span>
          </div>
          <div class="menu-item" @click="toOverdraftRuleManagement">
            <i class="fas fa-exclamation-triangle"></i>
            <span>透支规则</span>
          </div>
          <div class="menu-item" @click="toVipLevelManagement">
            <i class="fas fa-crown"></i>
            <span>VIP等级</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div class="loading" v-if="loading">
      <i class="fas fa-spinner fa-spin"></i>
      <p>加载统计数据中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { userAPI } from '@/api/user.js'
import { applicationAPI } from '@/api/application.js'
import { businessAPI } from '@/api/business.js'

const router = useRouter()
const authStore = useAuthStore()

const userInfo = ref({})
const stats = ref({
  userCount: 0,
  pendingApplications: 0,
  businessCount: 0,
  orderCount: 0
})
const loading = ref(false)

// 页面加载时获取用户信息和统计
onMounted(async () => {
  await loadUserInfo()
  await loadStats()
})

// 加载用户信息 - 修改后的函数
const loadUserInfo = async () => {
  try {
    const response = await userAPI.getActualUser()
    console.log('用户信息完整响应:', response)

    // 简化数据处理逻辑
    let data = null

    // 根据实际响应结构调整
    if (response.data && response.data.success === true && response.data.data) {
      // 如果后端返回 { success: true, code: 'OK', data: {...}, message: null }
      data = response.data.data
    } else if (response.data && response.data.id) {
      // 如果后端直接返回 User 对象
      data = response.data
    } else {
      // 其他情况
      data = response.data
    }

    console.log('提取的用户数据:', data)

    if (data) {
      userInfo.value = data
    } else {
      console.error('未获取到用户数据')
      userInfo.value = {}
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    userInfo.value = {}
  }
}

// 加载统计数据 - 修改后的函数
const loadStats = async () => {
  loading.value = true
  try {
    // 并行调用所有统计接口
    const [usersResponse, applicationsResponse, businessesResponse, ordersResponse] = await Promise.all([
      userAPI.getTotalUsers(),
      userAPI.getPendingApplications(),
      userAPI.getTotalBusinesses(),
      userAPI.getTotalOrders()
    ])

    console.log('统计接口响应:', {
      users: usersResponse,
      applications: applicationsResponse,
      businesses: businessesResponse,
      orders: ordersResponse
    })

    // 统一处理响应数据提取
    const extractData = (response) => {
      if (response.data && response.data.success === true && response.data.data !== undefined) {
        return response.data.data
      } else if (response.data !== undefined) {
        return response.data
      }
      return 0
    }

    // 更新统计数据
    stats.value = {
      userCount: extractData(usersResponse) || 0,
      pendingApplications: extractData(applicationsResponse) || 0,
      businessCount: extractData(businessesResponse) || 0,
      orderCount: extractData(ordersResponse) || 0
    }

    console.log('提取的统计数据:', stats.value)
  } catch (error) {
    console.error('获取统计信息失败:', error)
    // 如果统计接口失败，使用默认值
    stats.value = {
      userCount: 0,
      pendingApplications: 0,
      businessCount: 0,
      orderCount: 0
    }
    alert('获取统计信息失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 跳转到用户管理
const toUserManagement = () => {
  router.push('/admin/users')
}

// 跳转到新增用户
const toAddUser = () => {
  router.push('/admin/users?action=addUser')
}

// 跳转到新增自然人
const toAddPerson = () => {
  router.push('/admin/users?action=addPerson')
}

// 跳转到申请列表
const toApplicationList = () => {
  router.push('/admin/applications')
}

// 跳转到待审核申请
const toPendingApplications = () => {
  router.push('/admin/applications?status=0')
}

// 跳转到店铺管理
const toBusinessManagement = () => {
  router.push('/admin/businesses')
}

// 跳转到提现规则管理
const toWithdrawRuleManagement = () => {
  router.push('/admin/withdraw-rules')
}

// 跳转到充值规则管理
const toRechargeRuleManagement = () => {
  router.push('/admin/recharge-rules')
}

// 跳转到透支规则管理
const toOverdraftRuleManagement = () => {
  router.push('/admin/overdraft-rules')
}

// 跳转到VIP等级管理
const toVipLevelManagement = () => {
  router.push('/admin/vip-levels')
}

// 退出登录
const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    authStore.logout()
    router.push('/login')
  }
}
</script>


<style scoped>
.admin-dashboard {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20px;
  position: relative;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0;
  color: #333;
  font-size: 24px;
}

.header-left p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.logout-btn {
  background: #ff4757;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: white;
}

.user-stat { background: linear-gradient(135deg, #667eea, #764ba2); }
.application-stat { background: linear-gradient(135deg, #f093fb, #f5576c); }
.business-stat { background: linear-gradient(135deg, #4facfe, #00f2fe); }
.order-stat { background: linear-gradient(135deg, #43e97b, #38f9d7); }

.stat-info h3 {
  margin: 0;
  font-size: 28px;
  color: #333;
  font-weight: bold;
}

.stat-info p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.admin-menu {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.menu-section h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 18px;
  padding-left: 10px;
  border-left: 4px solid #ee5a24;
}

.menu-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.menu-item {
  background: white;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  position: relative;
}

.menu-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0,0,0,0.15);
}

.menu-item i {
  font-size: 24px;
  color: #ee5a24;
  width: 30px;
  text-align: center;
}

.menu-item span {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.badge {
  background: #ff4757;
  color: white;
  border-radius: 10px;
  padding: 2px 8px;
  font-size: 12px;
  position: absolute;
  top: 10px;
  right: 10px;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #999;
  z-index: 10;
}

.loading i {
  font-size: 48px;
  margin-bottom: 10px;
  color: #ee5a24;
}

.loading p {
  font-size: 16px;
}

@media (max-width: 768px) {
  .admin-dashboard {
    padding: 10px;
  }

  .header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }

  .stats-cards {
    grid-template-columns: 1fr;
  }

  .menu-grid {
    grid-template-columns: 1fr;
  }
}
</style>